package yxy.game.pm2.command.tower;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TowerMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.tower.TowerHandle;
import yxy.game.pm2.module.tower.TowerModule;

import java.util.Collection;

/** 修炼塔 扫荡 */
@MessageType(proto = Command.TowerSweep, classtype = TowerMessage.TowerSweepRequest.class)
public class CMD_TowerSweep extends Command<TowerMessage.TowerSweepRequest> {

	@Override
	public void execute(MessageSource messageSource, TowerMessage.TowerSweepRequest request) {
		String playerCode = messageSource.getTag();
		int floor = request.getFloor();

		TowerMessage.TowerSweepResponse.Builder response = TowerMessage.TowerSweepResponse.newBuilder();

		TowerModule towerModule = TowerModule.get(playerCode);
		try {
			if (towerModule.tryLock()) {
				if (floor > towerModule.getFloor()) {
					send(messageSource, response, Result.TowerCantSweepFloor);// 这层还没有挑战成功，不能扫荡
					return;
				}

				if (towerModule.remainTimes() <= 0) {
					if (towerModule.remainBuyTimes() <= 0) {
						send(messageSource, response, Result.TowerChanllengeTimesLack);// 没有挑战次数了
						return;
					}
					int cost = TowerHandle.buytimescost(towerModule.getBuytimes());
					try {
						new CurrencyHandle().cost(playerCode, CCReason.修炼塔, Currency.create(CurrencyType.CT_元宝, 0, cost));
					} catch (CurrencyNotEnoughException e) {
						send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
						return;
					}
					// 购买了一次挑战
					towerModule.setBuytimes(towerModule.getBuytimes() + 1);
					towerModule.setTimes(towerModule.getTimes() - 1);
				}

				towerModule.setTimes(towerModule.getTimes() + 1);
				towerModule.set();
				TaskHandle.handle(playerCode, TaskType.统计型_修炼塔_挑战_次数, 1);

				Collection<Currency> rewards = TowerHandle.floorRewards(floor, false);
				new CurrencyHandle().addCurrency(playerCode, CCReason.修炼塔, rewards);
				response.addAllRewards(new CurrencyHandle().packItems(rewards));

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			towerModule.unlock();
		}
	}

	private void send(MessageSource messageSource, TowerMessage.TowerSweepResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}